package com.tanhua.server.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.utils.Cache;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class RedisCacheInterceptor implements HandlerInterceptor {
    @Value("${tanhua.cache.enable}")
    private Boolean enabkle;
    @Autowired
    private RedisTemplate redisTemplate;
    //创建一个json转换工具
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
//缓存全局开关的校验
        //默认是false 放行
        if (!enabkle) {
            return true;
        }
        //校验handler 是否是HandlerInterceptor  不是就放行
        if (!(handler instanceof HandlerInterceptor)) {
            return true;
        }

        //判读是否是get请求
        if (!((HandlerMethod) handler).hasMethodAnnotation(GetMapping.class)) {
            return true;
        }
        //判断是否是添加了@Ccahe注解 不是就不拦截
        if (!((HandlerMethod) handler).hasMethodAnnotation(Cache.class)) {
            return true;
        }
        //缓存命中 利用一些规则生成redistoken key
        String redisKey = createRedisKey(request);
        //String cacheDate = this.redisTemplate.opsForValue().get(redisKey);
        String cacheData = (String) this.redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(cacheData)) {
            //缓存没命中
            return true;
        }
        //缓存命中 表示数据在redis库里面
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(cacheData);
        return false;
    }

    /**
     * 生成redis中的key ,规则SERVER_CACHE_DATA_MD5(url + param + token
     *
     * @param request
     * @return
     */
    public static String createRedisKey(HttpServletRequest request) throws JsonProcessingException {
        String url = request.getRequestURI();
        String param = MAPPER.writeValueAsString(request.getParameterMap());
        //获取token数据
        String token = request.getHeader("Authorization");
        String data = url + "_" + param + "_" + token;
        return "SERVER_CACHE_DATA_MD5" + data;
    }
}
